package com.example.demo.sample;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

/**
 * @author void
 * @date 2021/5/18 18:57
 * @desc
 */
@Profile("simple")
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder myPasswordEncoder;

    /**
     * 配置授权服务器的安全，意味着/oauth/token 和 /oauth/authorize 端点是安全的
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        super.configure(security);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //配置client和密码
                .withClient("client-for-server")
                .secret(myPasswordEncoder.encode("client-for-server"))
                //授权类型
                .authorizedGrantTypes("authorization_code", "implicit")
                //设置该client的access_token的有效期7200s，需要小于可刷新时间
                .accessTokenValiditySeconds(7200)
                .refreshTokenValiditySeconds(72000)
                .redirectUris("http://localhost:8080/login/oauth2/code/authorizationserver")
                .additionalInformation()
                //该client可访问的资源服务器的id
                .resourceIds(ResourceServerConfig.RESOURCE_ID)
                //client拥有的权限，资源服务器基于定义权限鉴权
                .authorities("ROLE_CLIENT")
                .scopes("profile", "email", "phone", "aaa")
                //自动批准的范围
                .autoApprove("profile");
    }

    /**
     * 可自定义获取code的端点，获取access_token的端点，定义token service
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        super.configure(endpoints);
    }
}
